﻿using System;
using System.Web;

using OctoOS;
using OctoOS.UI;

public partial class __editPage : OOSPage
{
	class PathInfo
	{
		[PathInfoMember(0)]
		[RangeValidator(1, Int64.MaxValue)]
		[IntegerBase(64)]
		internal long ArticleID = 0;

		[PathInfoMember(1, true)]
		internal long PageID = 0;
	}

	PathInfo _pathInfo;

	protected void Page_Init(object sender, EventArgs e)
	{
		_pathInfo = EnablePathInfo<PathInfo>();
	}

    protected void Page_Load(object sender, EventArgs e)
    {
		AddBreadcrumb("", "/");
		AddBreadcrumb(Resources.Main.shared_MyArticlesLink, Urls.GetMyArticles());
		AddBreadcrumb(Resources.Main.shared_EditArticleLink, Urls.GetEditArticle(_pathInfo.ArticleID));

		if(!IsPostBack)
		{
			var article = ApiService.GetArticle(OOSRequest.Current, _pathInfo.ArticleID);

			if(!OOSRequest.Current.IsModerator &&
				article.UserID != OOSRequest.Current.UserID)
			{
				throw new HttpException();
			}

			if(_pathInfo.PageID == 0)
			{
				PageTitle = Resources.Main.editPage_AddTitle;
			}
			else
			{
				PageTitle = Resources.Main.editPage_EditTitle;
				var page = article.GetPage(_pathInfo.PageID, true);

				name.Text = page.Title;
				status.SelectedValue = page.Status.ToString();
			}
		}
    }

	protected void SubmitClick(object sender, EventArgs e)
	{
		if(IsValid)
		{
			if(_pathInfo.PageID == 0)
			{
				ApiService.InsertPage(OOSRequest.Current, _pathInfo.ArticleID,
					name.TrimmedText,
					(CompleteStatus)Enum.Parse(typeof(CompleteStatus), status.SelectedValue));
			}
			else
			{
				ApiService.UpdatePage(OOSRequest.Current, _pathInfo.ArticleID,
					_pathInfo.PageID, name.TrimmedText,
					(CompleteStatus)Enum.Parse(typeof(CompleteStatus), status.SelectedValue));
			}

			Response.Redirect(Urls.GetEditArticle(_pathInfo.ArticleID));
		}
	}
}